package com.lw.leetcode.other.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 1615. 最大网络秩
 *
 * @author liw
 * @version 1.0
 * @date 2022/7/2 11:45
 */
public class MaximalNetworkRank {

    public int maximalNetworkRank(int n, int[][] roads) {
        int[] arr = new int[n * n];
        int[][] counts = new int[n][2];
        for (int i = 0; i < n; i++) {
            counts[i][0] = i;
        }
        for (int[] road : roads) {
            int a = Math.min(road[1], road[0]);
            int b = Math.max(road[1], road[0]);
            arr[n * a + b] = 1;
            counts[a][1]++;
            counts[b][1]++;
        }
        Arrays.sort(counts, (a, b) -> Integer.compare(b[1], a[1]));
        int max = 0;
        for (int i = 0; i < n; i++) {
            int[] as = counts[i];
            for (int j = i + 1; j < n; j++) {
                int[] bs = counts[j];
                int c = as[1] + bs[1];
                if (c <= max) {
                    break;
                }

                c = c - arr[Math.min(as[0], bs[0]) * n + Math.max(as[0], bs[0])];
                max = Math.max(max, c);
            }
        }
        return max;
    }

}
